Iterators and Generators Homework

Problem 1

Create a generator that generates the squares of numbers up to some number N.


In [3]:
def gensquares(N):
    for i in range(N): 
        yield i**2

In [4]:
for x in gensquares(10):
    print x


0
1
4
9
16
25
36
49
64
81

Problem 2

Create a generator that yields "n" random numbers between a low and high number (that are inputs). Note: Use the random library. For example:


In [5]:
import random

random.randint(1,10)


Out[5]:
2

In [6]:
def rand_num(low,high,n):
    for i in range(n+1):
        yield random.randint(low, high)

In [7]:
for num in rand_num(1,10,12):
    print num


7
1
3
5
5
9
2
1
2
7
4
2
7

Problem 3

Use the iter() function to convert the string below


In [9]:
s = 'hello'

#code here
for letter in iter(s):
    print letter


h
e
l
l
o

Problem 4

Explain a use case for a generator using a yield statement where you would not want to use a normal function with a return statement.

A generator, utilizing a yield statement, returns an iterator object. The iterator object will yield/return a value each time it is called upon to iterate through its code. So in cases where a return statement would be used to return the entirely of a list, the generator would only return the current iteration of the list, remembering its state where it was last yielded.

Extra Credit!

Can you explain what gencomp is in the code below? (Note: We never covered this in lecture! You will have to do some googling/Stack Overflowing!)


In [10]:
my_list = [1,2,3,4,5]

gencomp = (item for item in my_list if item > 3)

for item in gencomp:
    print item


4
5

Hint google: generator comprehension is!

Great Job!

a generator expression is similar to a list comprehension. However it returns a generator rather than a list. Syntactically they are very similar with the exception being that list comps use [] and gen comps use ().